package repository

import (
	"context"
	"fmt"
	"webook/internal/repository/cache"
	"webook/internal/repository/dao"
)

type InterActiveRepository interface {
	IncrReadCnt(context context.Context, biz string, bizId int64) error
	IncrLike(ctx context.Context, biz string, articleId int64, userId int64) error
	DecrLike(ctx context.Context, biz string, articleId int64, userId int64) error
}

type CachedInteractiveRepository struct {
	dao   dao.InterActiveDAO
	cache cache.InterActiveCache
}

func NewCachedInteractiveRepository(dao dao.InterActiveDAO, cache cache.InterActiveCache) InterActiveRepository {
	return &CachedInteractiveRepository{
		dao:   dao,
		cache: cache,
	}
}

func (c *CachedInteractiveRepository) DecrLike(ctx context.Context, biz string, articleId int64, userId int64) error {
	err := c.dao.DecrLike(ctx, biz, articleId, userId)
	if err != nil {
		return err
	}
	var key = fmt.Sprintf("interactive:%s:%d", biz, articleId)
	// 有记录更新缓存
	go func() {
		er := c.cache.DecrLikeCntIfPresent(ctx, key, "like_cnt", -1)
		if er != nil {
			// TODO 记录日志（更新点赞数缓存失败）
		}
	}()
	return nil
}

func (c *CachedInteractiveRepository) IncrLike(ctx context.Context, biz string, articleId int64, userId int64) error {
	err := c.dao.IncrLike(ctx, biz, articleId, userId)
	if err != nil {
		return err
	}
	var key = fmt.Sprintf("interactive:%s:%d", biz, articleId)
	// 有记录更新缓存
	go func() {
		er := c.cache.IncrLikeCntIfPresent(ctx, key, "like_cnt", 1)
		if er != nil {
			// TODO 记录日志（更新点赞数缓存失败）
		}
	}()
	return nil
}

func (c *CachedInteractiveRepository) IncrReadCnt(context context.Context, biz string, bizId int64) error {
	err := c.dao.IncrReadCnt(context, biz, bizId)
	if err != nil {
		return err
	}
	// 有记录才更新缓存
	var key = fmt.Sprintf("interactive:%s:%d", biz, bizId)
	return c.cache.IncrReadCntIfPresent(context, key, "read_cnt", 1)
}
